<template>
  <div>
    姓名: <input v-model="form.name" type="text"><br>
    年龄: <input v-model="form.age" type="text"><br>
    性别:
    <select v-model="form.gender">
      <option value="男">男</option>
      <option value="女">女</option>
    </select><br>
    <button @click="add">添加</button>
    <button @click="modify">修改</button>
    <br>
    <table border>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>&nbsp;
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
    form:{
        name:'',
      gender:'',
      age:'',
      id:'',
    },
      arr: [
        { id: 11, name: 'Tom', gender: '男', age: 19 },
        { id: 22, name: 'Jone', gender: '女', age: 21 },
      ]
    }
  },
  methods:{
    add(){
      //1当用户点击添加时先做非空校验
      // 三个变量任意一个是空都不能通过
      const {name,age,gender}=this.form
      if(age === ''||gender === ""||age === "")return alert('请输入数据')

      //2添加 将三个数据组成对象，加入到数组
      this.arr.push({
       name,
       gender,
       age,
       id:Date.now()
      })
       
       //清空表单
       this.form={
        name:'',
        age:'',
        gender:''
       }
      
    },
    edit(id){
      const obj=this.arr.find(item=>item.id ===id)
      this.form = {...obj}
    },
    modify(){
      //1找到当前要修改的数据 id
      const id =this.form.id
      //2根据id找到对应的数据
      const obj = this.arr.find(item=>item.id === id)
      //3修改数据
      //obj和arr数组中的 tom 对象 指向同一地址 所以修改会影响数组中的tom
      obj.name=this.form.name
      obj.age=this.form.age
      obj.gender=this.form.gender
    },
    del(id){
   const index=this.arr.findIndex(item=>item.id===id)
   this.arr.splice(index,1)
    }
  }
}
</script>

<style scoped>
table {
  /* border: 1px solid black; */
  border-collapse: collapse;
}
td, th {
  padding: 10px;
}
</style>